package goodroommate.ui.comment;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import goodroommate.domain.User;
import goodroommate.exception.DatabaseException;
import goodroommate.service.ICommentService;
import goodroommate.service.impl.CommentService;

/**
 * Servlet implementation class AddCommentServlet
 */
@WebServlet("/Comment/AddComment")
public class AddCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    ICommentService commentService=new CommentService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCommentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("user");
		if(user==null){
			response.sendRedirect(request.getContextPath()+"/Account/Login");
			return;
		}
		
		String action= request.getParameter("action");
		int reply=0,postingid=0;
		try{
			
			if(action!=null&&"comment".equals(action)){
				
				String strPostingID=request.getParameter("postingID");
				String content=request.getParameter("commentcontent");
				try{
					postingid=Integer.parseInt(strPostingID);
				}catch(NumberFormatException e){
					
				}
				try{
					commentService.addComment(user.getId(), 0, postingid, content);
					response.sendRedirect(request.getContextPath() + "/Posting/ShowPosting?postingid=" + postingid);
					return;
				}catch(DatabaseException e){
					
				}
			}
			
			if(action!=null&&"reply".equals(action)){
				
				String strPostingID=request.getParameter("postingID");
				String content=request.getParameter("replycontent");
				String strReply=request.getParameter("replytag");
				
				
				try{
					reply=Integer.parseInt(strReply);
				}catch(NumberFormatException e){
					
				}
				try{
					postingid=Integer.parseInt(strPostingID);
				}catch(NumberFormatException e){
					
				}
				
				
				try{
					commentService.addComment(user.getId(),reply, postingid, content);
					response.sendRedirect(request.getContextPath() + "/Posting/ShowPosting?postingid=" + postingid);
					return;
				}catch(DatabaseException e){
					
				}
				
				
			}
			
		}catch(Exception e){
			
		}		
	}

}
